package iopackage

import (
	"bufio"
	"encoding/json"
	"fmt"
	"io"
	"os"
)

func test1() {
	var s1, s2 string
	fmt.Scanf("%s,%s", &s1, &s2)
	fmt.Println(s1, s2)
	input := "hello,world"
	format := "%s,%s"
	fmt.Sscanf(input, format, &s1, &s2)
	fmt.Println(s1, s2)
}

func test2() {
	inputReader := bufio.NewReader(os.Stdin)
	input, err := inputReader.ReadString('#')
	if err != nil {
		fmt.Println("error")
		return
	}
	fmt.Println(input)
}

func test3() {
	inputFile, fileErr := os.Open("test.dat")
	if fileErr != nil {
		fmt.Println("open fail error")
	}
	defer inputFile.Close()

	inputReader := bufio.NewReader(inputFile)
	for {
		inputString, inputErr := inputReader.ReadString('#')
		if inputErr == io.EOF {
			return
		}
		fmt.Println(inputString)
	}
}

func test4() {
	// 获取到文件的句柄
	outfile, outerror := os.OpenFile("output.dat", os.O_WRONLY|os.O_CREATE, 0666)
	if outerror != nil {
		fmt.Println("create fail")
		return
	}
	defer outfile.Close()

	// 用文件的句柄初始化写对象
	outWriter := bufio.NewWriter(outfile)

	str := "hello world\n"

	for i := 0; i < 10; i++ {
		// 利用写对象，向文件当中写数据
		_, err := outWriter.WriteString(str)
		if err != nil {
			fmt.Println("error")
			return
		}
		fmt.Println("write success: ", str)
	}

	err := outWriter.Flush()
	if err != nil {
		fmt.Println("error")
		return
	}
}

func test5() {
	fmt.Fprintf(os.Stdout, "%s\n", "hello go fprintf")
	buf := bufio.NewWriter(os.Stdout)
	fmt.Fprintf(buf, "%s\n", "hello newwirter")
	buf.Flush()
}

type test6S1 struct {
	Firstname string
	Lastname  string
}

type test6S2 struct {
	First  string
	Second string
	Array  []*test6S1
}

func test6() {
	ts11 := &test6S1{"hello", "go"}
	ts12 := &test6S1{"hi", "cpp"}
	ts21 := test6S2{"this", "that", []*test6S1{ts11, ts12}}

	js, _ := json.Marshal(ts21)
	fmt.Printf("%s", js)
}

func Test() {
	test6()
}
